package cn.tjad.tjad2.net.http;

import android.text.TextUtils;
import android.util.Log;

import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.common.utils.JsonUtils;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.HttpId;
import com.qiandian.android.base.net.http.HttpRequest;
import com.qiandian.android.base.net.http.HttpUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.consts.UrlConsts;
import cn.tjad.tjad2.data.bean.LoginBean;
import cn.tjad.tjad2.data.session.Session;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;

public class TokenAuthenticator implements Authenticator {

    private static final String TAG = HttpConstants.TAG;

    @Override
    public Request authenticate(Route route, Response response) throws IOException {
        if (response.code() == 401) {
            Log.d(TAG, "token过期，需要重新登录");
            Session session = TjadApplication.getInstance().getSession();
            if (session == null) {
                return null;
            }
            String username = session.getAccount();
            String password = session.getPassword();
            if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                //账号密码为空，跳转到登陆页
            } else {
                Map<String, Object> params = new HashMap<>();
                params.put("username", username);
                params.put("password", password);
                HttpRequest request = new HttpRequest(HttpId.LOGIN, UrlConsts.USER_AUTH, params);
                Response loginResp = HttpUtils.doHttpRequestSync(request, "POST");
                if (loginResp.code() == 200) {
                    String responseStr = loginResp.body().string();
                    CommonBean<LoginBean> login = JsonUtils.parseObject(responseStr, LoginBean.class, CommonBean.class);
                    if (login != null && login.resCode == 0) {
                        saveSession(login.result);
                        return response.request().newBuilder().build();
                    } else {
                        //登录失败，跳转到登陆页
                    }
                } else {
                    //登录失败，跳转到登陆页
                }
            }
        }
        return null;
    }

    private void saveSession(LoginBean result) {
        Session session = TjadApplication.getInstance().getSession();
        if (session == null) {
            session = new Session();
        }
        session.setLoginInfo(result);
        TjadApplication.getInstance().setSession(session);

    }
}
